import 'package:cool_ui/cool_ui.dart';
import 'package:emby/model/api_response.dart';
import 'package:emby/model/login_info.dart';
import 'package:emby/model/user.dart';
import 'package:emby/util/api.dart';
import 'package:emby/util/function.dart';
import 'package:flutter/material.dart';

class Login extends StatefulWidget {
  @override
  _LoginState createState() => _LoginState();
}

class _LoginState extends State<Login> {
  List<User> users = [];
  String username;
  TextEditingController _usernameController;
  String password;
  @override
  void initState() {
    getData();
    super.initState();
  }

  getData() async {
    ApiResponse res = await Api.userPublic();
    if (res.code == 1) {
      setState(() {
        users = res.data;
      });
    } else {
      Util.toast(res.data);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("账号登录"),
      ),
      body: ListView(
        padding: EdgeInsets.symmetric(horizontal: 10),
        children: <Widget>[
          TextField(
            controller: _usernameController,
            decoration: InputDecoration(
              hintText: "请填写用户名",
              labelText: "用户名",
            ),
            onChanged: (v) => username = v,
          ),
          TextField(
            decoration: InputDecoration(
              hintText: "密码",
              labelText: "请填写密码",
            ),
            onChanged: (v) => password = v,
          ),
          SizedBox(
            height: 20,
          ),
          FlatButton(
            color: Theme.of(context).primaryColor,
            child: Text(
              "登录",
              style: TextStyle(color: Colors.white),
            ),
            onPressed: () async {
              var hide = showWeuiLoadingToast(context: context, message: Text("登录中"), alignment: Alignment.center, backButtonClose: true);
              ApiResponse res = await Api.authenticateByName(username, password);
              hide();
              if (res.code == 1) {
                LoginInfo loginInfo = res.data;
                await Util.setToken(loginInfo.accessToken);
                await Util.setUserId(loginInfo.user.id);
                Navigator.of(context).pushNamedAndRemoveUntil("/homePage", (route) => false);
              } else {
                Util.toast("用户名/密码有误");
              }
            },
          ),
          SizedBox(
            height: 20,
          ),
//          Text("快捷登录"),
        ],
      ),
    );
  }
}
